//
//  NetworkTools.swift
//  LEOweibo
//
//  Created by zz on 16/2/26.
//  Copyright © 2016年 zz. All rights reserved.
//

import Foundation
import AFNetworking

enum leoRequestType: String {
    case GET = "GET"
    case POST = "POST"
}
class NetworkTools : AFHTTPSessionManager  {
    
    
    
    //MARK:-             私有属性
    let appKey = "1094426883"
    let appSecret = "0711a92ab446d86482fe35a7c268b644"
    let redirectUri = "http://www.baidu.com"
//    let appKey = "3749801249"
//    let appSecret = "81b0bf80479524c5e6fc8d21b4d75d39"
//    let redirectUri = "http://www.baidu.com"
    var reachable: Bool {
        return reachabilityManager.reachable//AFNetworkReachabilityManager.sharedManager().reachable
    }
    ///单例实现
    static let sharedTools: NetworkTools = {
        
        let tools = NetworkTools(baseURL: nil)
        
        // 设置反序列化支持数据格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        // 设置 AFN 的网络 `请求` 超时
        tools.requestSerializer.timeoutInterval = 15
        

        // 将 JSON 中的 NULL 值过滤，有些第三方框架在做字典转模型时，如果遇到 NULL 值会崩溃！
        (tools.responseSerializer as! AFJSONResponseSerializer).removesKeysWithNullValues = true
        
        // 启动连接状态监听 - 通过通知中心发布的
        tools.reachabilityManager.startMonitoring()
        return tools
    }()
    
   //MARK:- AFN网络方法封装
    func request(leoType: leoRequestType, urlString: String, parameter:[String:AnyObject]?,finished:(result: [String: AnyObject]?) -> ()){
        //成功回调
        let success = {(task: NSURLSessionDataTask,response: AnyObject?) -> () in
            if let result = response as? [String: AnyObject] {
                
                finished(result: result)
            }else {
                finished(result: nil)
                print("数据格式错误")
            }
        }
        
        //失败回调
        let failure = {(task: NSURLSessionDataTask?,error: NSError) -> Void in
            
            print("网络请求失败")
            finished(result: nil)
        }
        
        if leoType == .GET {
            GET(urlString, parameters: parameter,progress: nil, success: success, failure: failure)
        }else{
            POST(urlString, parameters: parameter,progress: nil, success: success, failure: failure)
        }
        
        
    }
    
    
    
    
    
    
    
}